/*
 * Copyright (c) 2011 Imre Fazekas.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the Brillien nor the names of its
 * terms and concepts may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.vii.brillien.core.component.script;

import com.vii.brillien.core.component.SuperPresence;
import com.vii.brillien.core.management.BrillienServices;
import com.vii.brillien.ignition.transport.BrillienCommunication;
import com.vii.brillien.kernel.BrillienException;
import com.vii.brillien.kernel.annotations.PresenceService;
import com.vii.brillien.kernel.annotations.lifecycle.Resident;
import com.vii.streamline.annotation.P;
import com.vii.streamline.services.error.StreamLineException;
import com.vii.streamline.services.script.ScriptServices;
import sun.org.mozilla.javascript.internal.Function;
import sun.org.mozilla.javascript.internal.Scriptable;

import javax.script.ScriptContext;
import javax.script.ScriptEngine;

/**
 * Special Presence type representing a software-based Processor receiving behavior by scripts as parameter of a special received communication.
 */
@PresenceService( logLevel = PresenceService.CONFIG )
@Resident
public class Processor<R> extends SuperPresence<R> {

    protected ScriptEngine    engine;
    protected ScriptContext   context;

    protected String          assignmentName;
    protected float           assignmentVersion;
    protected String          scriptedAssignment;

    protected void initScripting(){
        log("Initiating scriptengine..." );

        engine  = ScriptServices.createScriptEngine();
        context = ScriptServices.createScriptContext( engine );

        engine.put( "presence", this );
    }

    /**
     * Getter method for field assignmentName
     */
    public String getAssignmentName() {
        return assignmentName;
    }

    /**
     * Getter method for field assignmentVersion
     */
    public float getAssignmentVersion() {
        return assignmentVersion;
    }

    /**
     * Getter method for field scriptedAssignment
     */
    public String getScriptedAssignment() {
        return scriptedAssignment;
    }

    /**
     * Assumes a new code to became the behavior of this Processor
     * @param scriptedAssignment code
     * @return Communication.DEFAULT_ANSWER
     * @throws BrillienException in any case of error
     */
    public String assume( @P(name="scriptedAssignment") String scriptedAssignment ) throws BrillienException {
        return this.assumed( "", 1.0f, scriptedAssignment );
    }

    /**
     * Assumes a new code to became the behavior of this Processor
     * @param scriptedAssignment code
     * @return Communication.DEFAULT_ANSWER
     * @throws BrillienException in any case of error
     */
    public String assumed( @P(name="assignmentName") String assignmentName, @P(name="assignmentVersion") float assignmentVersion, @P(name="scriptedAssignment")  String scriptedAssignment ) throws BrillienException {
        initScripting();

        log("Evaluating script:" + scriptedAssignment );
        try {
            ScriptServices.eval( engine, context, scriptedAssignment );
        } catch (StreamLineException e) {
            throw new BrillienException( e );
        }

        this.assignmentName     = assignmentName;
        this.assignmentVersion  = assignmentVersion;
        this.scriptedAssignment = scriptedAssignment;
        
        return BrillienServices.DEFAULT_ANSWER;
    }    

    @Override
    protected Object invokeMessageProcessor( BrillienCommunication message ) throws BrillienException {

        if( context != null ){
            try{
                String msg = getSubject(message);
                Object ff = context.getAttribute( msg );
                if( ff != null && ff != Scriptable.NOT_FOUND && (ff instanceof Function) ){
                    log("Invoking javascript code... " );
                    return ScriptServices.call( engine, context, msg, message.getParameters() );
                }
            } catch( Throwable t ){
                exceptionLog( Processor.class.getName(), "invokeMessageProcessor", t );
            }
        }

        return super.invokeMessageProcessor( message );
    }

}
